<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never">
      <el-form :inline="true" :model="dataForm">
        <el-form-item label="公司名称">
          <el-autocomplete clearable v-model="dataForm.companyName" :fetch-suggestions="querySearch"
            placeholder="请输入公司名称" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>
        </el-form-item>
        <el-form-item label="时间筛选">
          <el-date-picker v-model="dataForm.dateTime" type="daterange" class="time" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
            :picker-options="pickerOptionsItem"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-button @click="handleExport" type="warning" style="float:right">企业实际用水Excel导出</el-button>
      </el-form>
    </el-card>
    <el-card class="box-card" shadow="never">
      <div slot="header">
        <el-button type="primary" @click="handleEdit('new')">新增</el-button>
        <el-upload action accept=".xls, .word" :multiple="false" :limit="1" :show-file-list="false"
          :http-request="handleImport" :before-upload="beforeUpload" class="import_btn">
          <el-button>Excel导入</el-button>
        </el-upload>

        <el-button @click="handleTemDown" type="success" style="float:right">企业实际用水模板下载</el-button>
      </div>
      <!-- 数据展示 -->
      <el-table :data="tableData" :header-cell-style="{ background: '#f0f3fa', textAlign: 'center' }"
        style="width: 100%" :row-class-name="tableRowClassName" :cell-style="{ textAlign: 'center' }"
        @sort-change="sortChange"
      >
        <el-table-column prop="companyName" label="单位名称"></el-table-column>
        <el-table-column prop="companyTypeName" label="单位类型"></el-table-column>
        <el-table-column prop="companyAddress" label="单位地址"></el-table-column>
        <el-table-column prop="year" label="用水年份"></el-table-column>
        <el-table-column label="用水量(吨/年)" sortable="custom">
          <template slot-scope="scope">
            <span class="bule" @click="handleSee(scope.row)">{{ scope.row.totalWater }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="waterTypeName" label="用水类型"></el-table-column>
        <el-table-column prop="operator" label="填报人"></el-table-column>
        <el-table-column prop="createDate" label="填报日期"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" content="编辑">
              <i class="el-icon-edit" @click="handleEdit('edit', scope.row)"></i>
            </el-tooltip>
            <el-tooltip class="item" content="详情">
              <i class="el-icon-info" @click="handleEdit('info', scope.row)"></i>
            </el-tooltip>
            <el-tooltip class="item" content="删除" v-if="isData(scope.row)">
              <i class="el-icon-delete" @click="handleDelete(scope.row)"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="dataForm.page"
        :page-sizes="[10, 20, 40, 60]" :page-size="dataForm.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </el-card>
    <newWater ref="newWater" @updata="emptyFun"></newWater>
    <waterItem ref="waterItem"></waterItem>
  </div>
</template>

<script>
import newWater from './component/newWater.vue'
import waterItem from '@/components/waterItem/idnex.vue'
import {
  declareBySupervise,
  deleteWaterDeclareById,
  importWaterDeclare,
  downloadWaterDeclare,
  downloadReallyWaterAll
} from '@/api/other'
import { confirm } from '@/config/publicMethod'
export default {
  // 组件注册
  components: {
    newWater,
    waterItem,
  },
  data() {
    return {
      dataForm: {
        companyId: '',
        companyName: '',
        dateTime: [], // mixins中this.ShowDate(366), this.ShowDate(0)
        fieldSort:'',
        page: 1,
        pageSize: 10,
      },
      monthList: {},
      tableData: [],
      itemList: [],
      publicFlag: false,
      total: 0,
    }
  },
  mounted() {
    this.declareBySuperviseReq()
  },

  methods: {
    // querySearch()  该方法在混入中
    onSubmit() {
      this.dataForm.page = 1
      this.declareBySuperviseReq()
    },
    declareBySuperviseReq() {
      let data = {
        companyId: this.dataForm.companyId,
        createDateStart: this.dataForm.dateTime.length > 0 ? this.dataForm.dateTime[0] + ' 00:00:00' : '',
        createDateEnd: this.dataForm.dateTime.length > 0 ? this.dataForm.dateTime[1] + ' 23:59:59' : '',
        fieldSort: this.dataForm.fieldSort,
        page: this.dataForm.page,
        pageSize: this.dataForm.pageSize,
      }
      declareBySupervise(data).then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        const { total, list } = data
        this.total = total
        this.tableData = list
      })
    },
    // 用水量筛选
    sortChange(column) {
      const { order } = column
      this.dataForm.fieldSort =  order == 'ascending' ? '`totalWater` asc' : '`totalWater` desc'
      this.onSubmit()
    },
    handleEdit(type, item) {
      this.$nextTick((_) => {
        this.$refs.newWater.init(type, item)
      })
    },
    async handleDelete({ id }) {
      const res = await confirm('确定删除该数据')
      if (res) {
        deleteWaterDeclareById({ id }).then((res) => {
          const { code, msg } = res
          if (code !== '0000') return this.$message.error(msg)
          this.emptyFun()
        })
      }
    },
    handleTemDown() {
      downloadWaterDeclare().then((res) => {
        if (res.size) {
          let url = URL.createObjectURL(new Blob([res]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.download = '企业实际用水统计表(标准版).xls'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      })
    },
    handleImport(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      importWaterDeclare(formData).then((res) => {
        const { code, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.$message.success('数据导入成功!')
        this.emptyFun()
      })
    },

    // 上传之前（凭据资料）
    beforeUpload(file) {
      const isIMAGE =
        file.type === 'image/word' || 'image/WORD' || 'image/xls' || 'image/XLS'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return isIMAGE && isLt5M
    },
    emptyFun() {
      this.dataForm.companyId = ''
      this.dataForm.companyName = ''
      this.dataForm.page = 1
      this.dataForm.dateTime = [this.ShowDate(366), this.ShowDate(0)] // mixins中
      this.declareBySuperviseReq()
    },
    handleSee({ id }) {
      this.$refs.waterItem.init(id)
    },
    handleSelect(item) {
      this.dataForm.companyId = item.id
    },
    // 监听pageSize改变事件
    handleSizeChange(newSize) {
      this.dataForm.pageSize = newSize
      this.declareBySuperviseReq()
    },
    // 监听 页面值 改变的事件
    handleCurrentChange(newPage) {
      this.dataForm.page = newPage
      this.declareBySuperviseReq()
    },
    handleExport() {
      let data = {
        companyId: this.dataForm.companyId,
        createDateStart: this.dataForm.dateTime.length > 0 ? this.dataForm.dateTime[0] + ' 00:00:00' : '',
        createDateEnd: this.dataForm.dateTime.length > 0 ? this.dataForm.dateTime[1] + ' 23:59:59' : '',
        fieldSort: this.dataForm.fieldSort
      }
      downloadReallyWaterAll(data).then(res => {
        if (res.size) {
          let url = URL.createObjectURL(new Blob([res]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.download = this.dataForm.dateTime.length > 0 ? `企业实际用水(${this.dataForm.dateTime[0]}-${this.dataForm.dateTime[1]}).xls` : `企业实际用水.xls`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      })
    }
  },
}
</script>

<style lang='scss' scoped>
.import_btn {
  display: inline-block;
  margin-left: 20px;
}
</style>
